package rootpackege.spring.service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
public class MailService {
	@Autowired
	JavaMailSender mailSender;
	
	/**
	 * 发送简单的消息
	 */
	public void sendMail(String from , String to){
		//创建发送的消息体
		SimpleMailMessage msg = new SimpleMailMessage();
		
		msg.setFrom(from);
		msg.setTo(to);
		msg.setSubject("测试");
		msg.setText("测试消息主体");
		//发送消息
		mailSender.send(msg);
		System.out.println("邮件发送完成,通过收件邮箱查看邮件内容....");
	}
	
	public void sendImgMail(String from , String to) throws MessagingException{
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		/**
		 * arg1 = true 表示发送的内容是multipart类型的
		 * arg2 指定邮件内容的编码格式
		 */
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true,"utf-8");
		messageHelper.setFrom(from);
		messageHelper.setTo(to);
		messageHelper.setSubject("带附件的邮件");
		String cont =
				" <!DOCTYPE html>" +
				"		<html>" +
				"		<head>" +
				"		<meta charset=\"UTF-8\">" +
				"		</head>" +
				"		<body>" +
				"			<h1>html富文本邮件</h1>" +
				"			<img src=\"http://pic.616pic.com/ys_b_img/00/03/60/Cz5xjnFH3d.jpg\">" +
				"		</body>" +
				"		</html>";
		/**
		 * arg0 文本内容
		 * arg1 当文本内容是富文本时，置为true
		 */
		messageHelper.setText(cont, true);
		mailSender.send(mimeMessage);
		System.out.println("邮件发送完成,通过收件邮箱查看邮件内容....");
		
	}
}
